﻿using System.Data;
using System.Data.SqlClient;
using System.Linq;
using ECommon.Components;
using ECommon.Dapper;
using ESTAR.Domain.Auth;
using ESTAR.Infrastructure;
using MySql.Data.MySqlClient;

namespace ESTAR.Domain.Dapper.Auth
{
    [Component]
    public class UserIndexRepository : IUserInfoIndexRepository
    {
        private IDbConnection GetConnection()
        {
            return new MySqlConnection(ConfigSettings.EStarConnectionString[Constants.UserDbName]);
        }

        public void Add(UserInfoIndex index)
        {
            using (var connection = GetConnection())
            {
                connection.Open();
                connection.Insert(new
                {
                    UserId = index.UserId,
                    UserName = index.UserName
                }, Constants.UserIndexTable);
            }
        }

        public UserInfoIndex FindByUserName(string userName)
        {
            using (var connection = GetConnection())
            {
                connection.Open();
                var data = connection.QueryList(new { UserName = userName }, Constants.UserIndexTable).SingleOrDefault();
                if (data != null)
                {
                    return new UserInfoIndex(data.AccountId as string, userName);
                }
                return null;
            }
        }
    }
}
